
const { showLoading, hideLoading, showToast } = require('../utils/common');
const user = require('../utils/user')
const { wxLogin } = require('../services/auth')
const ENV = 'dev' // prod 生产 dev 测试
const baseUrl = ENV === 'prod' ? 'https://tuzhang.hzhaxing.com' : 'https://haxing-tuanzhang.bantiaoyu.cn'
// q9A6UDi3lvbeIvKAyBdk
function request(method, url, params, isShowLoading = true) {
  return new Promise((resolve, reject) => {
    isShowLoading && showLoading()
    wx.request({
      url: baseUrl + url,
      data: { code: user.getCode(), ...params },
      method: method || 'POST',
      header: {
        'content-type': 'application/json',
        'Access-Token': user.getToken()
      },
      success: function (res) {
        isShowLoading && hideLoading();
        if (res.data.status === 500) {
          showToast('服务器异常')
          return reject(res.data)
        }
        if (res.data.code == 200 || res.data.code == 600 || res.data.state == 0) {
          resolve(res.data)
        } else if (res.data.code == 610) {
          //长时间未登录，登录失效，重新获取code
          wxLogin()
        } else if (res.data.code == 401 || res.data.code == 510) {
          //token失效
          user.removeToken()
          user.updateUserInfo({ login: false })
          showToast(res.data.message)
          const pages = getCurrentPages();
          const curPage = pages[pages.length - 1];
          const route = curPage.route
          if (route.indexOf('login') === -1) {
            wx.redirectTo({ url: '/pages/login/index' })
          }
        } else {
          showToast(res.data.message || '网络异常')
          reject(res)
        }
      },
      fail: function (error) {
        showToast('网络异常')
        reject(error)
      }
    })
  })
}

/**
 * post请求调用  
 */
function postRequest(url, params) {
  return request("POST", url, params);
}

/**
 * get请求调用
 */
function getRequest(url, params) {
  return request("GET", url, params);
}

/**
 * post请求调用  
 */
function putRequest(url, params) {
  return request("PUT", url, params);
}

/**
 * post请求调用  
 */
function deleteRequest(url, params) {
  return request("DELETE", url, params);
}

// 1.通过module.exports方式提供给外部调用
module.exports = {
  postRequest,
  getRequest,
  putRequest,
  deleteRequest,
  request,
  baseUrl
}